$(document).ready(function () {
    予清空()
    观dom()
});

function 予清空() {
    $('input[type="text"], input[type="number"], input[type="password"]').each(function () {
        var $input = $(this);
        if ($input.data("clearable-added")) return;
        
        $input.data("clearable-added", true);
        if ($input.css("position") === "static") $input.css("position", "relative");

        // 创建清空按钮
        var $clearButton = $(`
            <button type="button" class="btn btn-default btn-sm a-clear-top">
                <i class="bi bi-x-circle"></i>
            </button>
        `)
        .css({
            position: "absolute",
            left: "50%",
            transform: "translateX(-50%)",
            top: "-20px",
            display: "none",
            zIndex: 100,
        })
        .insertAfter($input);

        let isButtonHover = false; // 记录按钮是否被悬停

        // 统一的按钮状态更新函数
        function updateButtonVisibility() {
            const value = $input.data("value") || $input.val();
            const hasValue = !!value && value.trim() !== "";
            const isInputFocused = $input.is(":focus");

            // 仅当有值且（输入框聚焦或按钮悬停）时显示按钮
            if (hasValue && (isInputFocused || isButtonHover)) {
                $clearButton.show();
            } else {
                $clearButton.hide();
            }
        }

        // 输入框聚焦/失焦事件
        $input.on("focus", updateButtonVisibility);
        $input.on("blur", function () {
            // 失焦时延迟检查，确保点击按钮时有足够时间
            setTimeout(updateButtonVisibility, 100);
        });

        // 按钮悬停事件
        $clearButton.on("mouseenter", function () {
            isButtonHover = true;
            updateButtonVisibility();
        });

        $clearButton.on("mouseleave", function () {
            isButtonHover = false;
            updateButtonVisibility(); // 离开按钮时检查是否隐藏
        });

        // 值变化事件（输入或程序赋值）
        $input.on("input change", updateButtonVisibility);

        // 点击按钮事件
        $clearButton.on("click", function (e) {
            e.stopPropagation();
            $input.val("").data("value", "");
            updateButtonVisibility();
        });
    });
}

function 观dom() {
    var observer = new MutationObserver(function (mutations) {
        mutations.forEach(function (mutation) {
            if (mutation.addedNodes.length) {
                $(mutation.addedNodes)
                    .find('input[type="text"], input[type="number"], input[type="password"]')
                    .each(function () {
                        予清空()
                    })
            }
        })
    })

    var config = {
        childList: true,
        subtree: true,
    }

    observer.observe(document.body, config)
}